package com.fangshicai.pro_test_05;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

public class NewsAdapter extends ArrayAdapter<News> {
    private List<News> mNewsData;
    private Context mContext;
    private int resourceId;


    public NewsAdapter(@NonNull Context context, int resource, @NonNull List<News> data) {
        super(context, resource, data);
        this.mContext = context;
        this.mNewsData = data;
        this.resourceId = resource;
    }
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        News news = getItem(position);
        View view;
        ViewHolder viewHolder;
        //自定义第一次创建
        if(convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            //viewHolder
            viewHolder = new ViewHolder();
            viewHolder.ivImage = view.findViewById(R.id.iv_image);
            viewHolder.Subtitle = view.findViewById(R.id.tv_subtitle);
            viewHolder.tvTitle = view.findViewById(R.id.tv_title);
            //通过setTag存放缓存
            view.setTag(viewHolder);

        }else {
            //若已创建则直接拿取
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }


        viewHolder.tvTitle.setText(news.getmTitle());
        viewHolder.Subtitle.setText(news.getmAuthor());
        viewHolder.ivImage.setImageResource(news.getmImageId());
        return view;
    }


    class ViewHolder{
        TextView tvTitle;
        TextView Subtitle;
        ImageView ivImage;
    }
}
